package com.edu.base.ums.clsSchool.controller;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.edu.base.ums.clsSchool.domain.ClsSchool;
import com.edu.base.ums.clsSchool.service.IClsSchoolService;
import com.edu.common.city.domain.City;
import com.edu.common.city.service.ICityService;
import com.edu.common.county.domain.County;
import com.edu.common.county.service.ICountyService;
import com.edu.common.provice.domain.Province;
import com.edu.common.provice.service.IProvinceService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.UUIDUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;

/**
 * 学校Controller
 * 
 * @author lzs
 * @date 2021-02-09
 */
@RestController
@RequestMapping("/cls/clsSchool")
public class ClsSchoolController extends BaseController
{
	@Autowired
	private IClsSchoolService clsSchoolService;
	
	 @Autowired
	private IProvinceService provinceService;

	@Autowired
	private ICityService cityService;

	@Autowired
	private ICountyService countyService;

    /**
     * 查询学校列表
     */
    @PreAuthorize("@ss.hasPermi('cls:clsSchool:list')")
    @GetMapping("/list")
    public TableDataInfo list(ClsSchool clsSchool)
	{
		startPage();
		List<ClsSchool> list = clsSchoolService.selectClsSchoolList(clsSchool);
		if (CollectionUtils.isNotEmpty(list)) {
			List<Province> listProvince = provinceService.selectProvinceList(new Province());

			for (ClsSchool c : list) {
				if (StringUtils.isNotBlank(c.getProvCode())) {
					c.setProvName(listProvince.stream().filter((a) -> c.getProvCode().equals(a.getProvCode()))
							.collect(Collectors.toList()).get(0).getChineseName());
				}
				if (StringUtils.isNotBlank(c.getCityCode()) && StringUtils.isNotBlank(c.getProvCode())) {
					TableDataInfo tdcity = this.getCityByProvinceId(c.getProvCode());
					@SuppressWarnings("unchecked")
					List<City> listCity = (List<City>) tdcity.getRows();
					c.setCityName(listCity.stream().filter((a) -> c.getCityCode().equals(a.getCityCode()))
							.collect(Collectors.toList()).get(0).getChineseName());

				}

				if (StringUtils.isNotBlank(c.getCountryCode()) && StringUtils.isNotBlank(c.getCityCode())
						&& StringUtils.isNotBlank(c.getProvCode())) {
					TableDataInfo tdCounty = this.getCountyByCityId(c.getCityCode());
					@SuppressWarnings("unchecked")
					List<County> listCounty = (List<County>) tdCounty.getRows();
					c.setCountryName(listCounty.stream().filter((a) -> c.getCountryCode().equals(a.getCountyCode()))
							.collect(Collectors.toList()).get(0).getChineseName());
				}
			}

		}
		return getDataTable(list);
	}

    /**
     * 导出学校列表
     */
    @PreAuthorize("@ss.hasPermi('cls:clsSchool:export')")
    @Log(title = "学校", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(ClsSchool clsSchool)
    {
        List<ClsSchool> list = clsSchoolService.selectClsSchoolList(clsSchool);
        ExcelUtil<ClsSchool> util = new ExcelUtil<ClsSchool>(ClsSchool.class);
        return util.exportExcel(list, "clsSchool");
    }

    /**
     * 获取学校详细信息
     */
    @PreAuthorize("@ss.hasPermi('cls:clsSchool:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        return AjaxResult.success(clsSchoolService.selectClsSchoolById(id));
    }

    /**
     * 新增学校
     */
    @PreAuthorize("@ss.hasPermi('cls:clsSchool:add')")
    @Log(title = "学校", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ClsSchool clsSchool)
    {
    	if(org.apache.commons.lang.StringUtils.isBlank(clsSchool.getId())) {
    		clsSchool.setId(UUIDUtils.getUUID());
    		clsSchool.setCreateBy(String.valueOf(SecurityUtils.getLoginUser().getUser().getUserId()));
    		clsSchool.setCreateDate(new Date());
     	}
    	if(org.apache.commons.lang.StringUtils.isNotBlank(clsSchool.getSchoolName())) {
    		Map<String,String> map = this.getSchoolList();
    		if(map.containsValue(clsSchool.getSchoolName())) {
    			  return AjaxResult.error("学校名称已存在");
    		}
    	}
    	clsSchool.setDelFlag("0");
        return toAjax(clsSchoolService.insertClsSchool(clsSchool));
    }
    
    private  Map<String,String> getSchoolList(){
    	List<ClsSchool> list = clsSchoolService.selectClsSchoolList(new ClsSchool());
    	return list.stream().collect(Collectors.toMap(ClsSchool::getId, ClsSchool::getSchoolName));
    }

    /**
     * 修改学校
     */
    @PreAuthorize("@ss.hasPermi('cls:clsSchool:edit')")
    @Log(title = "学校", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ClsSchool clsSchool)
    {
    	clsSchool.setUpdateBy(String.valueOf(SecurityUtils.getLoginUser().getUser().getUserId()));
		clsSchool.setUpdateDate(new Date());
		if(org.apache.commons.lang.StringUtils.isNotBlank(clsSchool.getSchoolName())) {
    		Map<String,String> map = this.getSchoolList();
    		if(map.containsValue(clsSchool.getSchoolName())&& !map.containsKey(clsSchool.getId())) {
    			  return AjaxResult.error("学校名称已存在");
    		}
    	}
        return toAjax(clsSchoolService.updateClsSchool(clsSchool));
    }

    /**
     * 删除学校
     */
    @PreAuthorize("@ss.hasPermi('cls:clsSchool:remove')")
    @Log(title = "学校", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids)
    {
        return toAjax(clsSchoolService.deleteClsSchoolByIds(ids));
    }
    
    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('cls:clsSchool:edit')")
    @Log(title = "学校管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody  ClsSchool clsSchool)
    {
    	clsSchool.setUpdateBy(String.valueOf(SecurityUtils.getLoginUser().getUser().getUserId()));
        return toAjax(clsSchoolService.updateUserStatus(clsSchool));
    }
    
    /**
     *  查询所有省份
     * @return
     */
    @PreAuthorize("@ss.hasPermi('cls:clsSchool:query')")
    @GetMapping("/getProvinceList")
    public TableDataInfo getProvinceList()
    {
        List<Province> list = provinceService.selectProvinceList(new Province());
        return getDataTable(list);
    }
    
    /**
     *  查询该省下的城市
     * @return
     */
    @PreAuthorize("@ss.hasPermi('cls:clsSchool:query')")
    @GetMapping("/getCityByProvinceId/{provinceId}")
    public TableDataInfo getCityByProvinceId(@PathVariable("provinceId") String provinceId)
    {
    	City city=new City();
    	city.setProvinceCode(provinceId);
        List<City> list = cityService.selectCityList(city);
        return getDataTable(list);
    }
    
    /**
     *  查询该城市下的区县@PathVariable
     * @return
     */
    @PreAuthorize("@ss.hasPermi('cls:clsSchool:query')")
    @GetMapping("/getCountyByCityId/{cityId}")
    public TableDataInfo getCountyByCityId(@PathVariable("cityId") String cityId)
    {
    	County county = new County();
    	county.setCityCode(cityId);
        List<County> list = countyService.selectCountyList(county);
        return getDataTable(list);
    }
    
    @PreAuthorize("@ss.hasPermi('cls:clsSchool:query')")
    @GetMapping("/getSchoolList")
    public AjaxResult getSchoolList1()
	{
 		List<ClsSchool> list = clsSchoolService.selectClsSchoolList(new ClsSchool());
		if (CollectionUtils.isNotEmpty(list)) {
			List<Province> listProvince = provinceService.selectProvinceList(new Province());

			for (ClsSchool c : list) {
				if (StringUtils.isNotBlank(c.getProvCode())) {
					c.setProvName(listProvince.stream().filter((a) -> c.getProvCode().equals(a.getProvCode()))
							.collect(Collectors.toList()).get(0).getChineseName());
				}
				if (StringUtils.isNotBlank(c.getCityCode()) && StringUtils.isNotBlank(c.getProvCode())) {
					TableDataInfo tdcity = this.getCityByProvinceId(c.getProvCode());
					@SuppressWarnings("unchecked")
					List<City> listCity = (List<City>) tdcity.getRows();
					c.setCityName(listCity.stream().filter((a) -> c.getCityCode().equals(a.getCityCode()))
							.collect(Collectors.toList()).get(0).getChineseName());

				}

				if (StringUtils.isNotBlank(c.getCountryCode()) && StringUtils.isNotBlank(c.getCityCode())
						&& StringUtils.isNotBlank(c.getProvCode())) {
					TableDataInfo tdCounty = this.getCountyByCityId(c.getCityCode());
					@SuppressWarnings("unchecked")
					List<County> listCounty = (List<County>) tdCounty.getRows();
					c.setCountryName(listCounty.stream().filter((a) -> c.getCountryCode().equals(a.getCountyCode()))
							.collect(Collectors.toList()).get(0).getChineseName());
				}
			}

		}
		 return  AjaxResult.success(list);
	}
    
    
    
}
